package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware.ActivitiesDTO;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsCompleteness;
import com.lance.answer.util.HttpUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * <p>拿到当前学生所有视频课程的链接<p>
 * <p>
 * <p>4-28 FIXME 课程讨论区的的帖子的ID还没获取到？？？？？？？？？？？？？？？？？？
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2022/4/19 14:47
 */
public class TestYiWangYiSaveUnVideotmp2222 {


    public static void main(String[] args) throws Exception {
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


          String userName = "2115001201896";
      //  String userName = "2251001204863";

        String pwd = "Ouchn@2021";
        //  String courseId = "14192";
        //   String courseId = "50000001086";
        // String courseId = "50000000896";
        // String courseId = "50000003127";
        //    String courseId = "50000000468";
        //       String courseId = "50000000490";
        //    String courseId = "50000000494";
      //  List<Long> courseIds = Lists.newArrayList(40000000852L);
       // List<Long> courseIds = Lists.newArrayList(40000000852L,40000000840L,40000000860L,40000000861L,40000000863L,40000000871L,40000000885L);
        List<Long> courseIds = Lists.newArrayList(
                17665L,//病理生理学
                20855L,//护理伦理学
                16868L,//理工英语4
                20856L,//护理科研方法
                14337l//形势与政策



        );


        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);


        // FIXME 要输入验证码
        Thread.sleep(10000);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();

        Thread.sleep(10000);


        for (Long courseId : courseIds) {
            study(driver, courseId);
        }


//
    }

    public static void study(WebDriver driver, Long courseId) throws InterruptedException {
        driver.get("https://lms.ouchn.cn/course/" + courseId + "/ng#/courseware");

        Thread.sleep(5000);
        int page = 1;
        int pageSize = 20;
        boolean hasNextPage = true;
        List<Long> videoIdIds = Lists.newArrayList();
        while (hasNextPage) {
            Courseware courseware = null;
            try {
                courseware = getUserCourseInfo(driver, courseId, page, pageSize);
            } catch (Exception e) {
                hasNextPage = false;
                e.printStackTrace();
            }

            System.err.println("???11:" + courseware.getActivities().size());
            for (ActivitiesDTO activitiesDTO : courseware.getActivities()) {
            //    if(activitiesDTO.getType().contains("video")){
                if(activitiesDTO.getType().equals("video")){
                    continue;
                }
                videoIdIds.add(activitiesDTO.getId());

            }
            if (page >= courseware.getPages()) {
                hasNextPage = false;
            } else {
                //  hasNextPage = false;
                page++;
            }
            Thread.sleep(5000);
        }




        // 已经完成的视频教程
        List<Long> completeLearningActivity = Lists.newArrayList();

        try {
            LmsCompleteness lmsCompleteness = getLmsCompleteness(driver, courseId);
            completeLearningActivity.addAll(lmsCompleteness.getCompletedResult().getCompleted().getLearningActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }



        for (Long videoId : videoIdIds) {

           if(completeLearningActivity.contains(videoId)){
               continue;
           }

            try {
                // https://lms.ouchn.cn/course/40000000852/learning-activity/full-screen#/40000261482
               driver.get("https://lms.ouchn.cn/course/"+courseId+"/learning-activity/full-screen#/"+videoId);
               Thread.sleep(5*1000);

                savePageInfo(driver,courseId,videoId);
                Thread.sleep(1000);

               createTopic(driver);
               Thread.sleep(1000);

               scanPagePdf(driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(5000);

        }

        System.err.println("end...............");

      //  Thread.sleep(2000000);
    }

    public static void scanPagePdf(WebDriver driver){
      try{
          WebElement we = Util.findByCssSelector(driver,"span[class='file-name ng-binding']");
          if(we!=null){
              we.click();
          }
      }catch (Exception e){

      }
    }

    public static void savePageInfo(WebDriver driver,long courseId,long videoId){
        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/"+videoId;
        String cookie = Util.getCookie(driver.manage().getCookies());
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/"+courseId+"/learning-activity/full-screen");
        heads.put(":method", "POST");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/activities-read/"+videoId);
        heads.put("accept", "application/json, text/plain, */*");
        try {
            System.err.println("11111111111:"+HttpUtil.post(postUrl,Maps.newHashMap(),cookie,heads));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void createTopic(WebDriver driver){
        try {
            WebElement we = Util.findByCssSelector(driver,"a[data-label=\"发表帖子\"]");
            if(we!=null){
                we.click();
                Thread.sleep(1000);
                driver.findElement(By.cssSelector("input[ng-model='topic.title']")).sendKeys("好好学习，天天向上");
                // driver.findElement(By.cssSelector("textarea[name='content']")).sendKeys("好好学习，天天向上");

                driver.findElement(By.cssSelector("div[class='topic-form-section main-area']")).
                        findElement(By.cssSelector("div[class='simditor']")).click();
                try {
                    driver.findElement(By.id("add-topic-popup")).findElement(By.cssSelector("div[class='simditor-body needsclick']")).sendKeys("好好学习，天天向上");
                }catch (Exception e){

                }
                for(WebElement saveWe:driver.findElement(By.id("add-topic-popup")).findElements(By.cssSelector("button[class='button button-green medium']"))){
                    if("保存".equals(saveWe.getText())){
                        saveWe.click();
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static LmsCompleteness getLmsCompleteness(WebDriver driver, Long courseId) throws Exception {
        String cookie = Util.getCookie(driver.manage().getCookies());
        String getUrl = "https://lms.ouchn.cn/api/course/" + courseId + "/my-completeness";
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/" + courseId + "/my-completeness");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        System.err.println("getLmsCompleteness:"+result);
        return JSON.parseObject(result, LmsCompleteness.class);
    }


    public static Courseware getUserCourseInfo(WebDriver driver, Long courseId, int page, int pageSize) throws Exception {


        String cookie = Util.getCookie(driver.manage().getCookies());

//        int page = 1;
//        int pageSize=20;
        String getUrl = "https://lms.ouchn.cn/api/course/" + courseId + "/coursewares?conditions=%7B%22category%22:null,%22itemsSortBy%22:%7B%22predicate%22:%22chapter%22,%22reverse%22:false%7D,%22ignore_activity_types%22:%5B%22lesson%22%5D%7D" +
                "&page=" + page + "&page_size=" + pageSize;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        //     heads.put(":path", "/api/course/" + courseId + "/activity-reads-for-user");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        System.err.println("result:::" + result);
        return JSON.parseObject(result, Courseware.class);
    }






    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }


    //   String js = "document.getElementByClassName(\"mvp-play-progress\").setAttribute(\"style\",\"width: 97.5%;\")";
//        String js = "$('.mvp-play-progress').css('style','width: 20.5%;') ";
//
//        ((JavascriptExecutor) driver).executeScript(js);

    // https://www.cnblogs.com/du-hong/p/15337826.html
//        Thread.sleep(2000);
//        Actions action = new Actions(driver);
//     //   WebElement target = driver.findElement(By.className("mvp-play-progress"));
//      //  WebElement target = findElementByCssSelector(driver,"div[class='mvp-play-progress']",20);
//        WebElement target = findElementByCssSelector(driver,"div[class='mvp-progress-control']",20);
//     //   action.dragAndDropBy(target,1000,0);
//       // action.contextClick(target).moveByOffset(990,0).perform();
//
//     System.err.println("x:"+   target.getLocation().x);
//     System.err.println("y:"+   target.getLocation().y);
//
//     WebElement t1 = driver.findElement(By.cssSelector("button[class='mvp-play-rate-btn']"));
//        System.err.println("t1x:"+   t1.getLocation().x);
//        System.err.println("t1y:"+   t1.getLocation().y);
//
//        action.contextClick(target).moveToElement(t1).perform();
//
//        Thread.sleep(2000000);

}
